import * as vscode from "vscode";
import { auth, nPost, ua, userData } from "@ap/util/request";
import { showErrorMessage } from "@ap/util/vscode/message";
import { arenaErrorMsg } from "@ap/util/vscode/errorMsg";
import { generatePrompt } from "@ap/types/aiChatCfg";
import { UserDataRootObject } from "@ap/types/config";
import { userDataToChat } from "./chatjpt";
import axios from "axios";

const decoder = new TextDecoder();

export async function handleCreateChat(
  message: {
    chatType: number;
    msg: string;
    chatOptions: string;
  },
  callback: (
    chatMsg: any,
    data: {
      auth: {};
      ua: {};
      userData: UserDataRootObject;
    }
  ) => void
) {
  const data = userDataToChat();
  if (data) {
    const resp = await axios.post(
      "https://api.fastgpt.in/api/v1/chat/completions",
      {
        chatId: message.chatOptions,
        stream: true,
        variables: {
          auth,
          ua,
          languageType: "TypeScript",
        },
        messages: [
          {
            role: "system",
            content: generatePrompt({
              chatType: message.chatType,
              languageType: "TypeScript",
            }),
          },
          {
            content: message.msg,
            role: "user",
          },
        ],
      },
      {
        headers: {
          Authorization:
            "Bearer fastgpt-bq00K2XrVUvxVQg1RkSPlzMqvM3K5Z70bO2YTruF9IuNmSWsxM22huZ4p5cYG",
          "Content-Type": "application/json",
        },
        responseType: "stream",
      }
    );

    const reader = resp.data;

    reader.on("data", (chunk: Buffer) => {
      const txt = decoder.decode(new Uint8Array(chunk));

      const dataParts = txt.split("data: ");

      dataParts.forEach((part, index) => {
        if (index === 0) {
          return;
        }

        const jsonPart = JSON.parse(part.trim());
        if (jsonPart) {
          callback(jsonPart, data);
        }
      });
    });

    await new Promise((resolve, reject) => {
      reader.on("end", resolve);
      reader.on("error", reject);
    });
  } else {
    showErrorMessage(arenaErrorMsg.LOG_IN_TO_THE_SHINJIMA_ACCOUNT);
  }
}

// 发送请求到FastGPT的知识库，仅查询知识库的内容
export async function onlyKnowledgeBase(msg: string) {
  const resp = await axios.post(
    "https://api.fastgpt.in/api/v1/chat/completions",
    {
      chatId: "knowledge-base",
      messages: [
        {
          content: msg,
          role: "user",
        },
      ],
    },
    {
      headers: {
        Authorization:
          "Bearer fastgpt-bq00K2XrVUvxVQg1RkSPlzMqvM3K5Z70bO2YTruF9IuNmSWsxM22huZ4p5cYG",
        "Content-Type": "application/json",
      },
      maxContentLength: Infinity,
    }
  );

  return resp.data;
}
